// pages/home/index.js

import {
    getBannersList,
    getPersonalized,
    getPlayListDetail,
    getRankingList,
} from '../../api/index'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperList: [],
    navList: [],
    recommendList: [],
    rankList: [],
    type:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getToLogin()
    this.getSwiperList()
    this.getNavContainerList()
    this.getRecommendList()
    this.getRankList()
  },

  getToLogin() {
    const token = wx.getStorageSync('token')
    !token && wx.navigateTo({ url: '/pages/login/index' })
  },

  async getSwiperList() {
    const { banners } = await getBannersList({ type: 2 })
    this.setData({ swiperList: banners })
  },

  // 导航
  getNavContainerList() {
    const data = [
      {
        icon: 'icon-meirituijian',
        title: '每日推荐',
        type: 'recommend'
      },
      {
        icon: 'icon-diantai',
        title: '歌单',
        type: 'playlist'
      },
      {
        icon: 'icon-paihangbang',
        title: '排行榜',
        type: 'ranking'
      },
      {
        icon: 'icon-diantai',
        title: '电台',
        type: 'radio'
      },
      {
        icon: 'icon-zhibo',
        title: '视频',
        type:'video'
      }
    ]
    this.setData({
      navList: data
    })
  },

  // 推荐歌曲
  async getRecommendList() {
    const { result } = await getPersonalized({ limit: 8 })
    this.setData({ recommendList: result })
  },

  // 排行榜
  async getRankList() {
    const  { list } = await getRankingList()
      const result = await Promise.all(list.slice(0,3).map(async (item) => {
			const { id, name } = item
			const { playlist } = await getPlayListDetail({ id })
			const trackList = playlist && playlist.tracks.slice(0,3)
			const singerList = trackList && trackList.map(item => item.ar)
			const singer =  singerList && singerList.length > 1 ?
                    singerList && singerList.map(item => item.map(item => item.name).join('/')) :
                    singerList && singerList[0].map(item => item.name)
			const tracks = trackList && trackList.map(item => item.al).map((item, index) =>{
				return {
					...item,
					singer: singer[index]
				}
			})
			return {
				id,
				name,
				tracks
			}
      }))
	  this.setData({ rankList: result })
  },

//  获取歌曲列表
  async handledTabsNav(event) {
    const { type } = event.currentTarget.dataset
    let url = ''
    switch (type) {
        case 'recommend':
            url =  `/pages/songs/songs?type=${type}`;
            break;
        default:
            url =  `/pages/songs/songs?type=${type}`;
    }
    wx.navigateTo({
        url
    })
  }

})  